const VueSticky = {
  bind(el, binding) {
    // sticky 元素固定相对屏幕高度
    const stickyTop = binding.value.stickyTop || 0
    // fixed 时 元素的z-index
    const zIndex = binding.value.zIndex || 1000
    const element = el

    element.style.position = '-webkit-sticky'
    element.style.position = 'sticky'
    // eslint-disable-next-line
    let source = decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent('source').replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
    if (~element.style.position.indexOf('sticky') && source !== 'android') {
      // 浏览器支持原生 sticky 效果（Currently Safari, Firefox and Chrome）
      element.style.top = `${stickyTop}px`
      element.style.zIndex = zIndex
      return
    }

    const elementChild = element.firstElementChild
    element.style.position = 'relative'
    elementChild.style.left = 0
    elementChild.style.right = 0
    elementChild.style.top = `${stickyTop}px`
    elementChild.style.zIndex = zIndex

    let active = false

    const check = () => {
      const offsetTop = element.getBoundingClientRect().top
      if (offsetTop <= stickyTop) {
        if (active) return
        if (!element.style.height) {
          element.style.height = `${element.clientHeight}px`
        }
        elementChild.style.position = 'fixed'
        active = true
      } else {
        if (!active) return
        elementChild.style.position = ''
        active = false
      }
    }

    let timer
    /* eslint-disable */
    el.__listenAction = () => {
      if (timer) return
      timer = setInterval(check, 30)
    }

    window.addEventListener('scroll', el.__listenAction)
  },
  unbind(el) {
    if (el.__listenAction) {
      window.removeEventListener('scroll', el.__listenAction)
    }
  },
}

export default VueSticky
